package com.beone.admin.security.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Title  验证码认证过滤器
 * @Author 覃忠君 on 2017/4/20.
 * @Copyright © 长笛龙吟
 */
public class ValidateCodeUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
    private String sessionvalidateCodeField = DEFAULT_SESSION_VALIDATE_CODE_FIELD;
    private String validateCodeParameter = DEFAULT_VALIDATE_CODE_PARAMETER;
    public static final String DEFAULT_SESSION_VALIDATE_CODE_FIELD = "validateCode";
    public static final String DEFAULT_VALIDATE_CODE_PARAMETER = "validateCode";

    public ValidateCodeUsernamePasswordAuthenticationFilter() {
        super(); //j_spring_security_check 登录验证Url生效
    }

    /**
     *  验证码认证
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        //验证码验证
        checkValidateCode(request);

        //口令认证
        return super.attemptAuthentication(request,response);
    }

    protected void checkValidateCode(HttpServletRequest request) throws AuthenticationException {
        String sessionValidateCode = obtainSessionValidateCode(request);
        String validateCodeParameter = obtainValidateCodeParameter(request);
        if (StringUtils.isBlank(validateCodeParameter)) {
            throw new AuthenticationServiceException("验证码不能为空！");
        }

        if(!sessionValidateCode.equalsIgnoreCase(validateCodeParameter)){
            throw new AuthenticationServiceException("验证码错误！");
        }
    }

    private String obtainValidateCodeParameter(HttpServletRequest request) {
        return request.getParameter(validateCodeParameter);
    }

    protected String obtainSessionValidateCode(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute(sessionvalidateCodeField);
        return null == obj ? "" : obj.toString();
    }

    public String getValidateCodeName() {
        return sessionvalidateCodeField;
    }

    public void setValidateCodeName(String validateCodeName) {
        this.sessionvalidateCodeField = validateCodeName;
    }
}